package org.psyduck.common.handler;

import com.alibaba.fastjson.JSON;
import org.psyduck.common.annotation.NotResponseAdvice;
import org.psyduck.common.model.JsonBean;
import org.psyduck.common.utils.Global;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 只处理org.psyduck包的
        return returnType.getExecutable().getDeclaringClass().getName().startsWith("org.psyduck.");
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        NotResponseAdvice notResponseAdviceByMethod = returnType.getMethodAnnotation(NotResponseAdvice.class);
        NotResponseAdvice notResponseAdviceByClass = returnType.getExecutable().getDeclaringClass().getAnnotation(NotResponseAdvice.class);

        if(null != notResponseAdviceByMethod || null != notResponseAdviceByClass || !Global.RESPONSE_ADVICE){
            return body;
        }

        response.getHeaders().setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE));

        if(body instanceof JsonBean) {
            return body;
        }

        JsonBean result = JsonBean.success(body);
        if(body instanceof String){
            return JSON.toJSONString(result);
        }

        if(selectedConverterType.getName().equals("org.springframework.http.converter.StringHttpMessageConverter") && null == body){
            return JSON.toJSONString(JsonBean.success(""));
        }

        return result;

    }
}